﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScrumTracker.Models;
using ScrumTracker.Helpers;
using System.Web.Helpers;
using System.IO;

namespace ScrumTracker.Controllers
{
    public class HourLogsController : Controller
    {
        //
        // GET: /Comments/

        public ActionResult Create(HourLog model)
        {
            model.CreatedAt = DateTime.UtcNow;
            //model.UserId = SessionHelper.CurrentUser.UserId;
            if (ModelState.IsValid)
            {
                var ctx = ScrumTrackerEntities.Instance;
                ctx.HourLogs.AddObject(model);
                ctx.SaveChanges();
                var list = ctx.HourLogs.Where(c => c.IssueId == model.IssueId).OrderByDescending(s => s.CreatedAt).AsEnumerable();
                return Json(new { success = true, html = RenderPartialViewToString(this, "_HourLogs", list) });
            }
            return Json(new { success = false });
        }

        public static string RenderPartialViewToString(Controller controller, string viewName, object model)
        {
            controller.ViewData.Model = model;
            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                    ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                    viewResult.View.Render(viewContext, sw);

                    return sw.GetStringBuilder().ToString();
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
    }
}
